<template>
  <div>
    <!--    <el-button type="primary" @click="delrouterall()">click</el-button>-->


    <div style="margin: 10px 0">
      <el-button size="small" type="primary" style="margin: 0 10px" @click="showNewForm">新增 <i
          class="el-icon-circle-plus"></i></el-button>
      <!--      <el-button type="primary" style="margin: 0 10px" @click="handleDelBatch">批量导入<i-->
      <!--          class="el-icon-upload"></i></el-button>-->
      <el-upload
          :show-file-list="false"
          style="display: inline-block"
          class="upload-demo"
          action="xx"
          :http-request="uploadFile"
          ref="upload"
      >
        <el-button size="small" type="primary" style="margin: 10px 10px">批量导入 <i
            class="el-icon-upload"></i></el-button>
      </el-upload>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='取消'
          icon="el-icon-info"
          icon-color="red"
          title="确定删除吗？"
          @confirm="handleDelBatch"
      >
        <el-button size="small" type="danger" slot="reference" style="margin: 10px 10px">
          批量删除
          <i class="el-icon-remove-outline"></i>
        </el-button>
      </el-popconfirm>
      <div style="float: right">
        <el-cascader
            style="margin-left: 10px; width: 255px"
            placeholder="请选择单位"
            ref="dwref"
            v-model="dwid"
            @change=""
            :options="dwoptions"
            :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id', emitPath: false }"
            clearable>
        </el-cascader>
        <el-input style="width: 200px; margin: 0 10px 0 10px" placeholder="请输入井号" suffix-icon="el-icon-search"
                  v-model="jh"/>

        <el-button type="primary" @click="search" icon="el-icon-search">搜索</el-button>
      </div>
      <!--        <el-button type="primary" style="margin: 0 10px" @click="batchImport">批量导入<i-->
      <!--            class="el-icon-upload"></i></el-button>-->
      <!--      </el-upload>-->

      <!--      <el-upload-->
      <!--          style="display: inline-block"-->
      <!--          class="upload-demo"-->
      <!--          action="http://localhost:9090/file/upload"-->
      <!--          accept='.xls,.xlsx'-->
      <!--          ref="upload"-->
      <!--      >-->
      <!--        <el-button type="primary" style="margin: 0 10px" @click="batchImport">批量导入<i-->
      <!--            class="el-icon-upload"></i></el-button>-->
      <!--      </el-upload>-->

      <!--      <el-popconfirm-->
      <!--          style="margin: 0 10px"-->
      <!--          confirm-button-text='确定'-->
      <!--          cancel-button-text='取消'-->
      <!--          icon="el-icon-info"-->
      <!--          icon-color="red"-->
      <!--          title="确定删除吗？"-->
      <!--          @confirm="handleDelBatch">-->
      <!--        <el-button type="danger" slot="reference" style="margin-left: 370px">批量删除<i-->
      <!--            class="el-icon-remove-outline"></i></el-button>-->
      <!--      </el-popconfirm>-->

    </div>


    <el-dialog title="新增" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="formRules" ref="saveform">
        <el-form-item label="井号" :label-width="formLabelWidth" prop="jh">
          <el-input v-model="form.jh" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="IP" :label-width="formLabelWidth" prop="ip">
          <el-input v-model="form.ip" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位" :label-width="formLabelWidth" prop="dw">
          <el-cascader
              style=" width: 255px"
              placeholder="请选择单位"
              ref="dwref"
              v-model="form.dw"
              @change="dwchange"
              :options="dwoptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id' }"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="干线" :label-width="formLabelWidth" prop="gx">
          <el-select style="" v-model="form.gx" clearable filterable placeholder="请选择干线">
            <el-option
                v-for="item in gxArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form :model="editform" :rules="editFormRules" ref="editform">
        <el-form-item label="井号" :label-width="formLabelWidth" prop="jh">
          <el-input v-model="editform.jh" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="IP" :label-width="formLabelWidth" prop="ip">
          <el-input v-model="editform.ip" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位" :label-width="formLabelWidth" prop="dw">
          <el-cascader
              emitPath: false
              style=" width: 255px"
              placeholder="请选择单位"
              ref="dwref"
              v-model="editform.dw"
              @change="dwchange"
              :options="dwoptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id' }"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="干线" :label-width="formLabelWidth" prop="gx">
          <el-select style="" v-model="editform.gx" clearable filterable placeholder="请选择干线">
            <el-option
                v-for="item in gxArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEidt">确 定</el-button>
      </div>
    </el-dialog>


    <!--    <el-dialog width="20%" title="停机确认！" :visible.sync="stopConfirmdialogFormVisible">-->
    <!--      确定要 {{ stopform.jh }}井 停机吗？-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="stopConfirmdialogFormVisible = false">取 消</el-button>-->
    <!--        <el-button type="primary" @click="stopCyj()">确 定</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->


    <el-table ref="table" @selection-change="handleSelectionChange" :data="tableData"
              style="margin: 10px; width: 1600px" border stripe>
      <el-table-column width="50" type="selection">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>

      <el-table-column prop="id" label="ID" width="60" v-if="false">
      </el-table-column>
      <el-table-column prop="jh" label="井号" width="200">
      </el-table-column>
      <el-table-column prop="ip" label="IP" width="150">
      </el-table-column>
      <el-table-column prop="dwObj.dwname" label="单位" width="200">
      </el-table-column>
      <el-table-column prop="gxObj.name" label="干线" width="200">
      </el-table-column>
      <!--      <el-table-column prop="role.roleName" label="角色" width="200">-->
      <!--      </el-table-column>-->
      <el-table-column prop="#" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="showEditForm(scope.row)">编辑 <i
              class="el-icon-edit"></i></el-button>
          <!--              <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i></el-button>-->

          <el-popconfirm
              style="margin: 0 10px"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="handleDel(scope.row.id)"
          >
            <el-button size="small" type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i>
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <!--    <el-popconfirm-->
    <!--        style="margin: 0 10px"-->
    <!--        confirm-button-text='确定'-->
    <!--        cancel-button-text='取消'-->
    <!--        icon="el-icon-info"-->
    <!--        icon-color="red"-->
    <!--        title="确定删除吗？"-->
    <!--        @confirm="handleDelBatch"-->
    <!--    >-->
    <!--      <el-button type="danger" slot="reference" style="margin: 10px">-->
    <!--        批量删除-->
    <!--        <i class="el-icon-remove-outline"></i>-->
    <!--      </el-button>-->
    <!--    </el-popconfirm>-->
    <!--    <div>-->
    <!--      <el-button round icon="el-icon-warning-outline" type="danger" style="margin: 10px" @click="showbathTjConfirmForm">-->
    <!--        批量停机-->
    <!--      </el-button>-->
    <!--    </div>-->
    <!--    <el-dialog width="20%" title="停机确认！" :visible.sync="batchstopConfirmdialogFormVisible">-->
    <!--      确定要批量停机吗？-->
    <!--      <div v-for="(item, index) in selectedRows"> {{ item.jh }}</div>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="batchstopConfirmdialogFormVisible = false">取 消</el-button>-->
    <!--        <el-button type="primary" @click="batchstopCyj()">确 定</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
    <div class="block" style="padding: 5px">
      <el-pagination

          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100,500,1000]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

  </div>

</template>
<script>
import service from "@/utils/request";
import ElementUI from "element-ui";

import VueRouter from 'vue-router'
import HomeView from "@/views/HomeView.vue";


export default {
  created() {
    this.load();
  },
  data() {
    return {
      dwoptions: [],
      dwid: null,
      dwval: [],
      jh: '',
      gx: null,
      gxArr: [],
      tableData: [],
      selectedRows: [], // 用来存储选中行的数据
      pageSize: 10,
      total: 100,
      currentPage: 1,
      dialogFormVisible: false,
      editFormVisible: false,
      form: {
        jh: '',
        ip: '',
        dw: '',
        gx: null
      },
      formRules: {
        jh: [
          {required: true, message: '请输入井号', trigger: 'blur'},
        ],
        ip: [
          {required: true, message: '请输入IP', trigger: 'blur'},
        ],
        dw: [
          {required: true, message: '请选择单位', trigger: 'blur'},
        ],
        gx: [
          {required: true, message: '请选择干线', trigger: 'blur'},
        ]
      },

      editform: {
        id: null,
        jh: '',
        ip: '',
        dw: '',
        gx: null
      },
      editFormRules: {
        jh: [
          {required: true, message: '请输入井号', trigger: 'blur'},
        ],
        ip: [
          {required: true, message: '请输入IP', trigger: 'blur'},
        ],
        dw: [
          {required: true, message: '请选择单位', trigger: 'blur'},
        ],
        gx: [
          {required: true, message: '请选择干线', trigger: 'blur'},
        ]
      },
      // stopform: {
      //   id: null,
      //   jh: '',
      //   ip: '',
      //   dw: ''
      // },
      formLabelWidth: '120px'
    }
  },
  methods: {
    test() {
      service.get('/dj/test', {}).then(
          response => {
            if (response.data.code == 20000) {

              this.$message.success(response.data.message)
            }
          }
      )

    },

    load() {
      service.get('/dw/getAll', {}).then(
          response => {
            if (response.data.code == 20000) {
              this.dwoptions = response.data.data
            }
          }
      )

      service.get('/dj/getpageBydwgxjh', {
        params: {
          pagesize: this.pageSize,
          pagenum: this.currentPage,
          jh: this.jh,
          dw: this.dwid,  //因为是拷贝的tj。vue，所以这个参数是多余的，置为空
          gx: null //因为是拷贝的tj。vue，所以这个参数是多余的，置为空
        }
      }).then(response => {
            if (response.data.code == 20000) {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
              this.currentPage = response.data.data.current;
              this.pageSize = response.data.data.size;
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );
      // service.get('/dj/getpage', {
      //   params: {
      //     jh: this.jh,
      //     pagesize: this.pageSize,
      //     pagenum: this.currentPage,
      //   }
      // }).then(response => {
      //       if (response.data.code == 20000) {
      //         this.tableData = response.data.data.records;
      //         this.total = response.data.data.total;
      //         this.currentPage = response.data.data.current;
      //         this.pageSize = response.data.data.size;
      //       }
      //     },
      //     error => {
      //       ElementUI.Message({
      //         message: error.message,
      //         type: 'error'
      //       })
      //     }
      // );
    },
    //一个函数同时给新建和编辑框用，所以代码含有2者的东西
    dwchange(dw) {
      console.log('dwchange:' + dw)
      this.gx = null;//新建框
      this.editform.gx = null;//编辑框
      if (dw.length > 0) {
        let dwTmp = dw[dw.length - 1]
        // if (dw.length > 1) {
        //   dwTmp = dw[1]
        // }
        // service.get('/gx/getlistbydw', {params: {dwid: dw[dw.length - 1]}}).then(
        service.get('/gx/getlistbydw1', {params: {dwid: dwTmp}}).then(
            response => {
              if (response.data.code == 20000) {
                this.gxArr = response.data.data;
              } else {
                this.$message.error(response.data.message)
              }
            }, error => {
              ElementUI.Message({
                message: error.message,
                type: 'error'
              })
            }
        )
      } else {
        this.gxArr = []
      }
    },

    // gxchange(gxval) {
    //   this.load()
    // },
    handleSelectionChange(selection) {
      // console.log(selection)
      // this.selectedRows = selection.map(row => row._row);
      this.selectedRows = selection
      // console.log(this.selectedRows)
    },
    batchstopCyj() {
      this.batchstopConfirmdialogFormVisible = false
      service.post('/dj/batchtj', this.selectedRows).then(response => {
            if (response.data.code == 20000) {
              this.$message.success('批量发送停机命令成功，请及时确认停机状态!');
              // this.load()
            } else {
              // this.$message.error(response.data.message)
              this.$alert(response.data.message, '批量停机错误！', {
                confirmButtonText: '确定',
                // callback: action => {
                //   this.$message({
                //     type: 'info',
                //     message: `action: ${ action }`
                //   });
                // }
              });
            }
          }, error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      )
    },


    showNewForm() {
      service.get('/role/getlist', {
        params: {}
      }).then(response => {
            this.roles = response.data
            this.form = {}
            this.dialogFormVisible = true
            this.$nextTick(() => {
              this.$refs["saveform"].clearValidate()
            })
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.load()
    },

    handleSave() {
      this.$refs.saveform.validate(valid => {
        if (!valid) {
          return false
        }
        let saveform = {}
        saveform.jh = this.form.jh
        saveform.ip = this.form.ip
        saveform.dw = this.form.dw == null ? null : this.form.dw[this.form.dw.length - 1]
        saveform.gx = this.form.gx
        service.post('/dj/save', saveform).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('success!');
            this.dialogFormVisible = false
            this.load()
          } else {
            this.$message.error("error")
            this.dialogFormVisible = false
          }
        })
      })

    },
    showConfirmForm(row) {
      // this.id = row.id
      // this.stopform.jh = row.jh
      // this.stopform.ip = row.ip
      // this.stopform.dw = row.dw
      // this.stopConfirmdialogFormVisible = true
    },
    //本函数非常复杂，主要是因为要处理编辑框的dw和gx的联动,
    // showEditForm2(row) {
    //   service.get('/dj/getById', {
    //     params: {
    //       id: row.id
    //     }
    //   }).then(response => {
    //     if (response.data.code == 20000) {
    //       this.editform.id = response.data.data.id
    //       this.editform.jh = response.data.data.jh
    //       this.editform.ip = response.data.data.ip
    //       this.editform.dw = response.data.data.dw
    //       this.editform.gx = response.data.data.gx
    //       return response
    //     } else {
    //       this.$message.error(response.data.message)
    //       throw new Error(response.data.message)
    //     }
    //   }).then(response => {
    //     return service.get('/dw/getPathByid', {
    //       params: {
    //         id: response.data.data.dw
    //       }
    //     })
    //   }).then(
    //       response2 => {
    //         if (response2.data.code == 20000) {
    //           this.editform.dw = response2.data.data
    //           return response2
    //         } else {
    //           this.$message.error(response2.data.message)
    //           throw new Error(response2.data.message)
    //         }
    //       },
    //   ).then(response2 => {
    //         return service.get('/gx/getlistbydw', {
    //           params: {
    //             dwid: this.editform.dw == null ? null : [this.editform.dw.length - 1]
    //           }
    //         })
    //       }
    //   ).then(
    //       response3 => {
    //         if (response3.data.code == 20000) {
    //           this.gxArr = response3.data.data
    //           this.editFormVisible = true
    //           return response3
    //         } else {
    //           this.$message.error(response3.data.message)
    //           throw new Error(response3.data.message)
    //         }
    //       }
    //   )
    // },
    //下面函数是对上面函数的改进.但是业务逻辑不对，下面改进
    // showEditForm(row) {
    //   service.get('/dj/getById', {
    //     params: {
    //       id: row.id
    //     }
    //   }).then(response => {
    //     if (response.data.code == 20000) {
    //       this.editform.id = response.data.data.id
    //       this.editform.jh = response.data.data.jh
    //       this.editform.ip = response.data.data.ip
    //       this.editform.dw = response.data.data.dw
    //       this.editform.gx = response.data.data.gx
    //       return service.get('/dw/getPathByid', {
    //         params: {
    //           id: response.data.data.dw
    //         }
    //       })
    //     } else {
    //       this.$message.error(response.data.message)
    //       throw new Error(response.data.message)
    //     }
    //   }).then(
    //       response2 => {
    //         if (response2.data.code == 20000) {
    //           this.editform.dw = response2.data.data
    //           return service.get('/gx/getlistbydw', {
    //             params: {
    //               dwid: this.editform.dw == null ? null : this.editform.dw[this.editform.dw.length - 1]
    //             }
    //           })
    //         } else {
    //           this.$message.error(response2.data.message)
    //           throw new Error(response2.data.message)
    //         }
    //       },
    //   ).then(
    //       response3 => {
    //         if (response3.data.code == 20000) {
    //           this.gxArr = response3.data.data
    //           this.editFormVisible = true
    //           return response3
    //         } else {
    //           this.$message.error(response3.data.message)
    //           throw new Error(response3.data.message)
    //         }
    //       }
    //   )
    // },
    //本函数非常复杂，主要是因为要处理编辑框的dw和gx的联动,
    showEditForm(row) {
      service.get('/dj/getById', {
        params: {
          id: row.id
        }
      }).then(response => {
        if (response.data.code == 20000) {
          this.editform.id = response.data.data.id
          this.editform.jh = response.data.data.jh
          this.editform.ip = response.data.data.ip
          this.editform.dw = response.data.data.dw
          this.editform.gx = response.data.data.gx
          return service.get('/dw/getPathByid', {
            params: {
              id: response.data.data.dw
            }
          })
        } else {
          this.$message.error(response.data.message)
          throw new Error(response.data.message)
        }
      }).then(
          response2 => {
            if (response2.data.code == 20000) {
              this.editform.dw = response2.data.data
              // let dwTmp = this.editform.dw[0]
              // if (this.editform.dw.length > 1) {
              //   dwTmp = this.editform.dw[1]
              // }
              let dwTmp = null
              if (this.editform.dw != null && this.editform.dw.length >= 1) {
                dwTmp = this.editform.dw[this.editform.dw.length - 1]
              }
              return service.get('/gx/getlistbydw1', {
                params: {
                  // dwid: this.editform.dw == null ? null : this.editform.dw[this.editform.dw.length - 1]
                  dwid: dwTmp
                }
              })
            } else {
              this.$message.error(response2.data.message)
              throw new Error(response2.data.message)
            }
          },
      ).then(
          response3 => {
            if (response3.data.code == 20000) {
              this.gxArr = response3.data.data
              this.editFormVisible = true
              this.$nextTick(() => {
                this.$refs["editform"].clearValidate()
              })
              return response3
            } else {
              this.$message.error(response3.data.message)
              throw new Error(response3.data.message)
            }
          }
      )
    },


// service.get('/role/getlist', {
//   params: {}
// }).then(response => {
//
//       this.roles = response.data
//       this.editform.id = row.id
//       this.editform.username = row.username
//       this.editform.password = ''
//       // this.editform.role = ''
//       if (row.role) {
//         for (var i = 0; i < this.roles.length; i++) {
//           if (this.roles[i].roleName == row.role.roleName) {
//             this.editform.roleid = this.roles[i].roleId
//           }
//         }
//       }
//       this.editdialogFormVisible = true
//     },
//     error => {
//       ElementUI.Message({
//         message: error.message,
//         type: 'error'
//       })
//     }
// );

// showbathTjConfirmForm() {
//   this.batchstopConfirmdialogFormVisible = true
//
// },
    handleEidt() {
      this.$refs.editform.validate(valid => {
        if (!valid) {
          return
        }
        let editformTmp = {}
        editformTmp.id = this.editform.id
        editformTmp.jh = this.editform.jh
        editformTmp.ip = this.editform.ip
        editformTmp.dw = this.editform.dw[this.editform.dw.length - 1]
        editformTmp.gx = this.editform.gx
        service.post('/dj/edit', editformTmp).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('success!');
            this.editFormVisible = false
            this.load()
          } else {
            this.$message.error("error")
            this.editdialogFormVisible = false
          }
        })
      })

    },
    handleDel(id) {
      service.delete('/dj?id=' + id).then(response => {
        this.$message.success('删除成功!');
        this.load()
      })
    },
    search() {
      // this.currentPage = 1
      this.load()
    },
    handleDelBatch() {
      service.post('/dj/delbatch', this.selectedRows).then(response => {
        if (response.data.code == 20000) {
          this.$message.success('删除成功!');
          this.load()
        } else {
          this.$message.error("error")
        }
      })
    },
    uploadFile(param) {
      //param中的file才是真正的文件体，用于传入axios上传方法的参数

      const header = {"content-type": "multipart/form-data"} //请求头设置，没必要加，axios看到formdata类型，会自动加上，
      let formData = new FormData();
      formData.append("file", param.file);
      service.post('/dj/import', formData).then(res => {
        if (res.data.code == 20000) {
          this.$message.success('导入成功!');
          this.load()
        } else {
          this.$alert(res.data.message, '导入错误！', {
            confirmButtonText: '确定',
          })
          this.load()
        }
      }, error => {
        this.$alert(error.message, '错误！', {
          confirmButtonText: '确定',
        })
      })
    },
    // batchImport() {
    //   this.$refs.upload.submit()
    // },
  }
}
</script>

<style scoped>

</style>
